package com.example.demo.business.task;

import com.example.demo.business.bean.enums.UserType;
import com.example.demo.business.dao.HUserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;

@Component
public class ScheduleTask {

    //mei1
    @Autowired
    private HUserDao userDao;

    private boolean initDown = false;

    //每天凌晨初始化非会员的看片次数
    //并且初始下会员 看会员到期没有
    //每周1初始化会员的下载次数
    @Scheduled(cron = "5 0 0 1/1 * ? ")
    public void initNormalViewCount(){
        initDown = false;
        if (LocalDate.now().getDayOfWeek().getValue() == 1){
            //如果是周一 那么初始化会员的下载次数
            initDown=true;
        }
        //每天凌晨初始化非会员的看片次数
        userDao.findAll().forEach(item->{
            boolean save =false;
            //是会员并且会员到期了
            if (item.getUserType() == UserType.Vip.num &&(System.currentTimeMillis()/1000>item.getVipDueTime())){
                item.setUserType(UserType.Normal.num);
                save =true;
            }
            //初始化看片次数
            if (!(item.getFreeNum() == item.getAllNum() && item.getAllNum()==item.getRemainNum())){
                save =true;
                item.setAllNum(item.getFreeNum());
                item.setRemainNum(item.getFreeNum());
            }

            if (initDown){
                //是会员 并且 剩余次数和总次数不相等
                if ((item.getRemainDown() != item.getAllDown()) && item.getUserType() == UserType.Vip.num){
                    item.setRemainDown(item.getAllDown());
                    save =true;
                }
            }
            if (save){
                userDao.save(item);
            }
        });

    }


}
